package com.ymatou.apigateway.service;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.security.KeyStore;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.ymatou.apigateway.parameter.AesUtil;
import com.ymatou.apigateway.parameter.OpenApiGetOrdersReq;
import com.ymatou.apigateway.parameter.OpenapiReq;
import com.ymatou.iapi.trading.operate.parameter.PlaceOrderResp;
import com.ymatou.iapi.trading.operate.parameter.PlaceOrderService;
import com.ymatou.iapi.trading.operate.parameter.enums.LogisticsTypeEnum;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymttest.business.service.OrderCallService;
import com.ymttest.business.service.PaymentProxyCallService;

public class OpenapiService {

	/**
	 * 
	 * 
	 * 生成MD5加密串
	*/
	public static String generateMD5(OpenapiReq openapiReq, String appSecret) {

		Map<String, String> map = new TreeMap<String, String>();
		map.put("app_id", openapiReq.getApp_id());
		map.put("method", openapiReq.getMethod());
		map.put("sign_method", openapiReq.getSign_method());
		map.put("auth_code", openapiReq.getAuth_code());
		map.put("timestamp", openapiReq.getTimestamp());
		map.put("nonce_str", openapiReq.getNonce_str());
		map.put("biz_content", openapiReq.getBiz_content());

		StringBuffer sb = new StringBuffer();

		Set es = map.entrySet();

		Iterator it = es.iterator();

		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k)
					&& !"app_secret".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("app_secret=" + appSecret);

		return AesUtil.getMd5(sb.toString()).toUpperCase();
	}

	/**
	 * 
	 * 
	 * 1.通过服务端提供的证书生成本地访问证书文件 
	 * eg :  keytool -import -noprompt -storepass changeit -alias openapi -file C:/Users/sunsheng/Desktop/ymatou.com.cer -keystore C:/Users/sunsheng/Desktop/myYmt.store
	*/

	public static void callOpenApiBySSL(OpenapiReq openapiReq) throws Exception {

		KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

		//加载证书文件  
		//		String fliename = System.getProperty("user.dir") + File.separator
		//				+ "resource" + File.separator + "openApicer.store";

		String fliename = System.getProperty("user.dir") + File.separator
				+ "resource" + File.separator + "openApicer.store";
		//		String fliename = "E:\\baidu.store";

		FileInputStream instream = new FileInputStream(new File(fliename));

		try {

			trustStore.load(instream, "changeit".toCharArray());

		} finally {

			instream.close();

		}

		SSLContext sslcontext = SSLContexts.custom()
				.loadTrustMaterial(trustStore).build();

		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
				sslcontext,

				SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

		// 带证书
		CloseableHttpClient httpclient = HttpClients.custom()

		.setSSLSocketFactory(sslsf)

		.build();

		// 不带证书
		//		CloseableHttpClient httpclient = new DefaultHttpClient();

		try

		{

			String url = String
					.format("https://open.ymatou.com/apigateway/v1?app_id=%s&method=%s",
							openapiReq.getApp_id(), openapiReq.getMethod());

			HttpPost httpPost = new HttpPost(url);

			httpPost.addHeader("Accept",
					"text/xml,text/javascript,text/html,application/json");

			httpPost.addHeader("Content-Type",
					"application/json; charset=UTF-8");

			String entityString = FormatUtil.beanToGSONString(openapiReq);

			StringEntity se = new StringEntity(entityString, HTTP.UTF_8);

			System.out.println("----------------------------------------");
			System.out.println(String.format("请求url:%s", url));
			System.out.println(String.format("请求报文:%s", entityString));

			((HttpPost) httpPost).setEntity(se);

			CloseableHttpResponse response = httpclient.execute(httpPost);

			try {

				HttpEntity entity = response.getEntity();

				System.out.println("----------------------------------------");

				System.out.println(String.format("返回状态code:%s",
						response.getStatusLine()));

				if (entity != null) {

					System.out.println(String.format("返回报文:%s",
							EntityUtils.toString(entity)));

				}

			} finally {

				response.close();

			}

		} finally {

			httpclient.close();

		}

	}

	/**
	 * 第三方支付
	 * @return
	 */
	public static PlaceOrderResp placeOrderAndPaid() {

		PlaceOrderService.logisticsType = LogisticsTypeEnum.BondedDelivery;

		PlaceOrderResp placeOrderResp = PlaceOrderService.placeOrder4();

		int userId = placeOrderResp.getUserId();
		int tradingId = placeOrderResp.getTradingId();

		BigDecimal price = placeOrderResp.getPayAmount();

		// 13 为 app国际支付宝，15 微信
		String payType = "13";
		int thirdTradingId = new OrderCallService().orderPayRequest(userId,
				BigDecimal.ZERO, tradingId, payType);
		// 支付网关支付回调交易
		try {
			PaymentProxyCallService.notifyCall(payType,
					String.valueOf(thirdTradingId), price.toString(), userId);

			Thread.sleep(3000);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return placeOrderResp;
	}
	public static void main(String... args) throws Exception {

		String app_id = "XTuxHsUX0d2Uv3rLdq";
		String app_secret = "7DCCFE8111E0EABF86AF2F7E38D60B779F8DEF103F9D7B11C2E96EFEF81791DEA5E834AFB9ED29391EDCC72874148C5E";
		String auth_code = "V5SqSWXxieU9Y6tuwy0LexzDVOUrs3mL";
		String app_method = "ymatou.order.list.get";

		OpenApiGetOrdersReq openApiGetOrdersReq = new OpenApiGetOrdersReq();

		openApiGetOrdersReq.setDate_type(1);
		openApiGetOrdersReq.setEnd_date("2017-08-10 17:45:15");
		openApiGetOrdersReq.setOrder_status("3");
		openApiGetOrdersReq.setPage_no(1);
		openApiGetOrdersReq.setPage_rows(10);
		openApiGetOrdersReq.setSort_type(1);
		openApiGetOrdersReq.setNeeds_delivery_info(true);
		openApiGetOrdersReq.setStart_date("2017-08-09 17:45:15");

		OpenapiReq openapiReq = new OpenapiReq();

		openapiReq.setMethod(app_method);
		openapiReq.setApp_id(app_id);

		openapiReq.setSign_method("MD5");
		openapiReq.setAuth_code(auth_code);
		openapiReq.setTimestamp("2017-11-29 09:00:15");
		openapiReq.setNonce_str("9766600700979402217096246554958");

		openapiReq.setBiz_content(new FormatUtil()
				.beanToGSONString(openApiGetOrdersReq));
		/*
				openapiReq.setSign(OpenapiService.generateMD5(openapiReq,
						AesUtil.decrypt(app_secret)));*/

		Logger.info("sign:"
				+ OpenapiService.generateMD5(openapiReq,
						AesUtil.decrypt(app_secret)));

		Logger.info("app_secret:" + AesUtil.decrypt(app_secret));
	}

}
